//
//  DrawingBoard.swift
//  L02DrawShapes
//
//  Created by liy on 2024/12/25.
//

import UIKit

class DrawingBoardView: UIView {
  var path = CGMutablePath()

  // 触摸绘制过程
  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
      let location = touch.location(in: self) // 触摸点坐标
      path.move(to: location)
    }
  }

  override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
      let location = touch.location(in: self)
      path.addLine(to: location)
      setNeedsDisplay()
    }
  }

  override func draw(_ rect: CGRect) {
    //		1.使用path方式画图
//    let ct = UIGraphicsGetCurrentContext()
//    var path = CGMutablePath()
//    path.move(to: CGPoint(x: 50, y: 400))
//    path.addLine(to: CGPoint(x: 150, y: 500))
//    path.addLine(to: CGPoint(x: 350, y: 300))
//    ct?.addPath(path)
//    ct?.strokePath()

    // 2.画板案例
    let ct = UIGraphicsGetCurrentContext()
    ct?.addPath(path)
    ct?.strokePath()
  }
}

#if DEBUG

  import SwiftUI

  struct DrawingBoardRepresentable: UIViewRepresentable {
    typealias UIViewType = DrawingBoardView

    func makeUIView(context: Context) -> UIViewType {
      let v = DrawingBoardView()
      v.backgroundColor = .white
      return v
    }

    func updateUIView(_ uiView: UIViewType, context: Context) {
    }
  }

  struct DrawingBoard_Previews: PreviewProvider {
    static var previews: some View {
      DrawingBoardRepresentable()
    }
  }

#endif
